package com.liaoban.app.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.liaoban.app.R;
import com.liaoban.app.adapter.CharmAdapter;
import com.liaoban.app.adapter.GlideImageLoader;
import com.liaoban.app.adapter.MFragmentPagerAdapter;
import com.liaoban.app.adapter.RecommendAdapter;
import com.liaoban.app.api.type.Anchor;
import com.liaoban.app.api.type.Band;
import com.liaoban.app.api.type.RecommendName;
import com.liaoban.app.api.type.event.LoginEvent;
import com.liaoban.app.api.type.event.LogoutEvent;
import com.liaoban.app.api.type.event.UpdateUserEvent;
import com.liaoban.app.api.type.request.RecommendRequest;
import com.liaoban.app.biz.CommonBiz;
import com.liaoban.app.constants.ConfigKey;
import com.liaoban.app.helper.ConfigHelper;
import com.liaoban.app.helper.ImageHelper;
import com.liaoban.app.ui.MainActivity;
import com.liaoban.app.ui.base.BaseFragment;
import com.liaoban.app.ui.login.LoginActivity;
import com.liaoban.app.ui.message.CallHistoryActivity;
import com.liaoban.app.ui.anchor.AnchorDetailActivity;
import com.liaoban.app.ui.mine.SetActivity;
import com.liaoban.app.ui.rank.SearchActivity;
import com.liaoban.app.util.CommonUtils;
import com.liaoban.app.widget.MyGridLayoutManager;
import com.liaoban.app.ui.message.MyP2PMessageActivity;
import com.netease.nim.uikit.event.P2PMessageEvent;
import com.youth.banner.Banner;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.http.Body;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment {
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tv_near_people_count)
    TextView tvNearPeopleCount;
    @BindView(R.id.rv_recommend)
    RecyclerView rvRecommend;
    @BindView(R.id.rv_charm)
    RecyclerView rvCharm;
    @BindView(R.id.tabs)
    TabLayout tabLayout;
    @BindView(R.id.content)
    ViewPager content;
    @BindView(R.id.layout_near)
    LinearLayout layoutNear;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.tv_bang)
    TextView tvBang;
    @BindView(R.id.layout_recommend)
    LinearLayout layoutRecommend;
    @BindView(R.id.view_line2)
    View viewLine2;
    @BindView(R.id.iv_avatar1)
    ImageView ivAvatar1;
    @BindView(R.id.iv_avatar2)
    ImageView ivAvatar2;
    @BindView(R.id.iv_avatar3)
    ImageView ivAvatar3;

    private List<com.liaoban.app.api.type.Banner> mBanners;
    private RecommendAdapter mRecommendAdapter;
    private CharmAdapter mCharmAdapter;
    private MFragmentPagerAdapter mMFragmentPagerAdapter;

    @Override
    protected int getLayoutResID() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View contentView) {
        setNeedOnBus(true);
        initBanner();
        initRecommend();
        initCharm();
        if (CommonBiz.getInstance().isLogin(getActivity())) {
            String src = ConfigHelper.getString(getActivity(), ConfigKey.USER_SRC);
            ImageHelper.load(ivAvatar, CommonUtils.getFullPic(src));
        } else {
            ivAvatar.setImageResource(R.mipmap.ic_default_pic);
        }
        showRunningDialog();
        setView();
        loadData();
    }

    private void setView() {
        String wuserStatus = ConfigHelper.getString(getActivity(), ConfigKey.USER_WUSER_STATUS);
        if (CommonBiz.getInstance().isLogin(getActivity()) && "1".equals(wuserStatus)) { //是主播
            //附近的人
            layoutNear.setVisibility(View.GONE);
            viewLine.setVisibility(View.GONE);
            //推荐主播
            layoutRecommend.setVisibility(View.GONE);
            rvRecommend.setVisibility(View.GONE);
            viewLine2.setVisibility(View.GONE);
            //富豪榜
            tvBang.setText("富豪榜");
        } else {
            //附近的人
            layoutNear.setVisibility(View.VISIBLE);
            viewLine.setVisibility(View.VISIBLE);
            startTask(CommonBiz.getInstance().nearUser(), listBaseResponse -> {
                for (int i = 0; i < listBaseResponse.data.size() & i < 3; i++) {
                    Anchor anchor = listBaseResponse.data.get(i);
                    switch (i) {
                        case 0:
                            ImageHelper.load(ivAvatar1, CommonUtils.getFullPic(anchor.getWuserSrc()));
                            break;
                        case 1:
                            ImageHelper.load(ivAvatar2, CommonUtils.getFullPic(anchor.getWuserSrc()));
                            break;
                        case 2:
                            ImageHelper.load(ivAvatar3, CommonUtils.getFullPic(anchor.getWuserSrc()));
                            break;
                    }
                    tvNearPeopleCount.setText("" + listBaseResponse.num);
                }
            });
            //推荐主播
            RecommendRequest recommendRequest = new RecommendRequest();
            recommendRequest.setType("1");
            startTask(CommonBiz.getInstance().recommend(recommendRequest), baseResponse -> {
                mRecommendAdapter.setNewData(baseResponse.data);
            });
            layoutRecommend.setVisibility(View.VISIBLE);
            rvRecommend.setVisibility(View.VISIBLE);
            viewLine2.setVisibility(View.VISIBLE);
            //魅力榜
            tvBang.setText("魅力榜");
        }
        //魅力榜
        startTask(CommonBiz.getInstance().band(), baseResponse -> {
            mCharmAdapter.setNewData(baseResponse.data);
        });
        //首页分类
        startTask(CommonBiz.getInstance().recommendName(), listBaseResponse -> {
            initViewPager(listBaseResponse.data);
        });
    }

    /**
     * 初始化轮播图
     */
    private void initBanner() {
        banner.setOnBannerListener(position -> {
            /*com.liaoban.app.api.type.Banner banner = mBanners.get(position);
            startActivity(WebActivity.newIntent(getActivity(), banner.getBanRemark()));*/
        });
    }

    /**
     * 推荐主播
     */
    private void initRecommend() {
        MyGridLayoutManager manager = new MyGridLayoutManager(getActivity(), 2);
        rvRecommend.setLayoutManager(manager);
        mRecommendAdapter = new RecommendAdapter(null);
        rvRecommend.setAdapter(mRecommendAdapter);
        mRecommendAdapter.setOnItemClickListener(this::itemClickAnchor);
    }

    private void itemClickAnchor(BaseQuickAdapter baseQuickAdapter, View view, int position) {
        if (!CommonBiz.getInstance().isLogin(getActivity())) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
            return;
        }
        Object obj = baseQuickAdapter.getData().get(position);
        if (obj instanceof Anchor) {
            Anchor anchor = (Anchor) obj;
            startActivity(AnchorDetailActivity.newIntent(getActivity(), String.valueOf(anchor.getWuserId())));
        } else if (obj instanceof Band) {
            Band band = (Band) obj;
            startActivity(AnchorDetailActivity.newIntent(getActivity(), String.valueOf(band.getCallWid())));
        }

    }

    /**
     * 魅力榜
     */
    private void initCharm() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvCharm.setLayoutManager(manager);
        mCharmAdapter = new CharmAdapter(null);
        rvCharm.setAdapter(mCharmAdapter);
        mCharmAdapter.setOnItemClickListener(this::itemClickCharm);
    }

    private void itemClickCharm(BaseQuickAdapter baseQuickAdapter, View view, int position) {
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.changeTab(1);
    }

    @OnClick(R.id.iv_charm_more)
    public void charmMore() {
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.changeTab(1);
    }

    private void initViewPager(List<RecommendName> recommendNames) {
        if (CommonUtils.isEmpty(recommendNames)) {
            return;
        }
        int size = recommendNames.size();
        Class[] classes = new Class[size];
        String[] strings = new String[size];
        Bundle[] bundles = new Bundle[size];
        for (int i = 0; i < size; i++) {
            RecommendName recommendName = recommendNames.get(i);
            classes[i] = ClassRecommendFragment.class;
            strings[i] = recommendName.getFormContent();
            bundles[i] = ClassRecommendFragment.getBundle(recommendName.getFormId());
        }
        mMFragmentPagerAdapter = new MFragmentPagerAdapter(getChildFragmentManager(), classes, strings, bundles);
        content.setAdapter(mMFragmentPagerAdapter);
        tabLayout.setupWithViewPager(content);
        tabLayout.setTabMode(TabLayout.LAYOUT_MODE_CLIP_BOUNDS);
        CommonUtils.setTabLayoutWidth(tabLayout, 13);
    }

    private void loadData() {
        //首页轮播图
        startTask(CommonBiz.getInstance().banner(), baseResponse -> {
            mBanners = baseResponse.data;
            List<String> picUrls = new ArrayList<>();
            for (com.liaoban.app.api.type.Banner banner : baseResponse.data) {
                picUrls.add(CommonUtils.getFullPic(banner.getBanImgUrl()));
            }
            banner.setImages(picUrls).setImageLoader(new GlideImageLoader()).start();
        });
    }

    @OnClick(R.id.iv_sound)
    public void sound() {
        startActivity(new Intent(getActivity(), CallHistoryActivity.class));
    }

    @OnClick({R.id.layout_near, R.id.iv_more})
    public void anchor() {
        startActivity(new Intent(getActivity(), AnchorActivity.class));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent loginEvent) {
        String src = ConfigHelper.getString(getActivity(), ConfigKey.USER_SRC);
        ImageHelper.load(ivAvatar, CommonUtils.getFullPic(src));
        setView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLogoutEvent(LogoutEvent logoutEvent) {
        ivAvatar.setImageResource(R.mipmap.ic_default_pic);
        setView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateUserEvent(UpdateUserEvent updateUserEvent) {
        if (ConfigKey.USER_SRC.equals(updateUserEvent.type)) {
            String src = ConfigHelper.getString(getActivity(), ConfigKey.USER_SRC);
            ImageHelper.load(ivAvatar, CommonUtils.getFullPic(src));
        }
    }

    @OnClick(R.id.iv_avatar)
    public void avatar() {
        if (!CommonBiz.getInstance().isLogin(getActivity())) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
            return;
        }
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.changeTab(4);
    }

    @OnClick(R.id.layout_search)
    public void search() {
        startActivity(new Intent(getActivity(), SearchActivity.class));
    }
}
